﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "StructureInstanceGrepUtil.h"
#include "AlgorithmBodyTopologyOperate.h"
#include "GbmpBuiltInParameterDefinitionsNew.h"
#include "GraphicsNodeUtils.h"
#include "IBody.h"
#include "IElementBasicInformation.h"
#include "IElementParameters.h"
#include "IElementPosition.h"
#include "IGenericElement.h"
#include "IGraphicsBRepBody.h"
#include "IGraphicsBRepFace.h"
#include "IGraphicsElementShape.h"
#include "IInstance.h"
#include "ILine3d.h"
#include "IParameter.h"
#include "IParameterDefinitionLibrary.h"
#include "IPlane.h"
#include "IStructureSlopeLine.h"
#include "IType.h"
#include "LevelUtils.h"
#include "StructureInstanceUtils.h"
#include "IPositionAssociatedPlane.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

OwnerPtr<IGraphicsElementShape> gcmp::StructureInstanceGrepUtil::GenerateFloorGrepFromBaseGrep(const IInstance* pInstance, const IGraphicsElementShape* pGRep)
{
    if (pInstance == nullptr)
        return false;

    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pGRep,L"opGrep为空",L"GDMPLab",L"2024-03-30");
    // 获取Body
    std::vector<const IGraphicsBRepBody*> bodies;
    std::vector<Matrix4d> transforms;
    OwnerPtr<IGraphicsElementShape> opCloneGrep = TransferOwnershipCast<IGraphicsElementShape>(pGRep->Clone());
    //
    GraphicsNodeUtils::CollectBRepBodies(pInstance->GetDocument(), pGRep, &bodies, &transforms);
    DBG_WARN_AND_RETURN_UNLESS(bodies.size() == 1 && transforms.size() == 1, opCloneGrep, L"Body应该只有一个",L"GDMPLab",L"2024-03-30");
    if (bodies.front() == nullptr)
        return false;

    OwnerPtr<IGraphicsBRepBody> opBody = TransferOwnershipCast<IGraphicsBRepBody>(bodies.front()->Clone());
    DBG_WARN_AND_RETURN_UNLESS(opBody.get(), opCloneGrep, L"opBody为空",L"GDMPLab",L"2024-03-30");
    IBody* pBody = opBody->GetGeometryFW();
    DBG_WARN_AND_RETURN_UNLESS(pBody, opCloneGrep, L"pBody为空",L"GDMPLab",L"2024-03-30");

    // 厚度


    const IElementBasicInformation* pElementBasicIfmt = pInstance->GetBasicInformation();
    if (pElementBasicIfmt == nullptr)
        return false;

    const IType* pType = pElementBasicIfmt->GetType();
    if (pType == nullptr)
        return false;

    const IElementParameters* pParameters = pType->GetElementParameters();
    if (pType == nullptr)
        return false;

    OwnerPtr<IParameter> paramW = pParameters->GetParameterByUid(PARAMETER_UID(FloorCoreThicknessBuiltInParameter));
    DBG_WARN_AND_RETURN_UNLESS(IParameter::IsValidParameter(paramW), nullptr, L"没楼板的厚度参数",L"GDMPLab",L"2024-03-30");
    double thickness = paramW->GetValueAsDouble();

    // 定位
    gcmp::ElementId planeId = gcmp::IElementPosition::GetAssociatedPlaneId(pInstance);
    double topAssociatedElevation(0.0);
    bool bOk = LevelUtils::GetLevelElevation(pInstance->GetDocument(), planeId, topAssociatedElevation);
    DBG_WARN_AND_RETURN_UNLESS(bOk, opCloneGrep, L"GetLevelElevation失败",L"GDMPLab",L"2024-03-30");
    double offset = 0.0;
    IPositionAssociatedPlane::GetBottomPlaneHeightOffset(pInstance, offset);
    Vector3d topCenterPt = Vector3d(0, 0, topAssociatedElevation + offset);
    Vector3d normal = Vector3d::UnitZ;

    Matrix4d matInverse;
    transforms.front().GetInverse(matInverse);
    // 坡度
    const IGenericElement* pGenericElement = quick_cast<IGenericElement>(StructureInstanceUtils::GetFloorSlopeLine(pInstance));
    if (pGenericElement)
    {
        const IStructureSlopeLine* pSlopeLine = quick_cast<IStructureSlopeLine>(pGenericElement->GetExternalObject());
        DBG_WARN_AND_RETURN_UNLESS(pSlopeLine, opCloneGrep, L"pSlopeLine为空",L"GDMPLab",L"2024-03-30");

        OwnerPtr<ILine3d> opSlopeLine3d = pSlopeLine->GetSlopeLine();
        DBG_WARN_AND_RETURN_UNLESS(opSlopeLine3d, opCloneGrep, L"opSlopeLine3d为空",L"GDMPLab",L"2024-03-30");
        opSlopeLine3d->Transform(transforms.front());
        topCenterPt = opSlopeLine3d->GetStartPoint();

        Vector3d slopAxis = opSlopeLine3d->GetDirection().Cross(Vector3d::UnitZ);
        normal = slopAxis.Cross(opSlopeLine3d->GetDirection());
        normal.Normalize();
    }

    Vector3d bottomCenterPt = topCenterPt - normal * thickness;

    // 根据定位、厚度和坡度，计算顶底切平面
    std::vector<OwnerPtr<IPlane>> opSectionPlanes;
    opSectionPlanes.emplace_back(IPlane::Create(topCenterPt, normal,
        Intervald(-Constants::MAX_MODEL_SIZE / 2.0, Constants::MAX_MODEL_SIZE / 2.0), Intervald(-Constants::MAX_MODEL_SIZE / 2.0, Constants::MAX_MODEL_SIZE / 2.0)));
    opSectionPlanes.emplace_back(IPlane::Create(bottomCenterPt, -normal,
        Intervald(-Constants::MAX_MODEL_SIZE / 2.0, Constants::MAX_MODEL_SIZE / 2.0), Intervald(-Constants::MAX_MODEL_SIZE / 2.0, Constants::MAX_MODEL_SIZE / 2.0)));
    opSectionPlanes[0]->Transform(matInverse);
    opSectionPlanes[1]->Transform(matInverse);
    
    // 获取上下端面
    std::vector<IGraphicsBRepFace*> topBottomFaces = StructureInstanceUtils::GetFloorTopBottomFaces(opBody.get());
    DBG_WARN_AND_RETURN_UNLESS(topBottomFaces.size() == 2, opCloneGrep, L"topBottomFaces为空",L"GDMPLab",L"2024-03-30");

    bOk = AlgorithmBodyTopologyOperate::FitBodyToTargetPlaneAlongVAxisWithoutTopoChange(opSectionPlanes[0].get(), pBody, topBottomFaces[0]->GetGmFaceFW());
    if (!bOk)
    {
        std::wstring strWarnMsg = std::wstring()
            .append(L"顶面：FitBodyToTargetedFace失败")
            .append(L"\n【Body】\n")
            .append(pBody->GetStringForDebug())
            .append(L" \n 【Top Plane】 \n")
            .append(opSectionPlanes[0]->GetStringForDebug());
        DBG_WARN(strWarnMsg,L"GDMPLab",L"2024-03-30");
        return opCloneGrep;
    }
    bOk = AlgorithmBodyTopologyOperate::FitBodyToTargetPlaneAlongVAxisWithoutTopoChange(opSectionPlanes[1].get(), pBody, topBottomFaces[1]->GetGmFaceFW());
    if (!bOk)
    {
        std::wstring strWarnMsg = std::wstring()
            .append(L"底面：FitBodyToTargetedFace失败")
            .append(L"\n【Body】 \n")
            .append(pBody->GetStringForDebug())
            .append(L"\n 【Bottom Plane】 \n")
            .append(opSectionPlanes[1]->GetStringForDebug());
        DBG_WARN(strWarnMsg,L"GDMPLab",L"2024-03-30");
        return opCloneGrep;
    }
    // 把Transform移到后面是了为了保证镜像效果，理论上先变换然后修改体和先修改原体然后再变换，得到最终的body是一样的;
    opBody->Transform(transforms.front());

    OwnerPtr<IGraphicsElementShape> opNewGRep = IGraphicsElementShape::Create(pGRep->GetRenderLayer());
    opNewGRep->SetFlags(pGRep->GetFlags());
    opNewGRep->SetPriorityOffset(pGRep->GetPriorityOffset());
    opNewGRep->AddChild(TransferOwnership(opBody));
    Box3d newGrepBox = GraphicsNodeUtils::CalculateGraphicsNodeBoundingBox(pInstance->GetDocument(), opNewGRep.get());
    opNewGRep->SetBox(newGrepBox);
    opNewGRep->SetElementId(pInstance->GetElementId());
    return opNewGRep;
}

void StructureInstanceGrepUtil::TransformGRep(IGraphicsElementShape* pGRep, const IElement* pElement)
{
    if (pGRep == nullptr)
        return;

    const IElementPosition *posBehavior = pElement->GetElementPosition();
    DBG_WARN_AND_RETURN_VOID_UNLESS(posBehavior, L"无效的指针posBehavior",L"GDMPLab",L"2024-03-30");
    Matrix4d mat = posBehavior->ComputeLocalToWorldCoordinateSystemTransformMatrix();

    if (mat.IsIdentity())
    {
        return;
    }

    pGRep->Transform(mat);
}